<?php
declare(strict_types=1);

namespace App\Task;

use App\Exception\BusinessException;
use App\Model\ContentItem;
use Hyperf\Crontab\Annotation\Crontab;
use Hyperf\Redis\Redis;
use Hyperf\Redis\RedisFactory;
use Hyperf\Utils\ApplicationContext;

/**
 * @Crontab(
 *     name="SaveViewedAndLikedCountTask",
 *     rule="*\/2 * * * *",
 *     callback="execute",
 *     singleton=true,
 *     onOneServer=true,
 *     mutexPool="default",
 *     mutexExpires=60,
 *     memo="保存查看数和点赞数入库"
 * )
 */
class SaveViewedAndLikedCountTask
{
    public function execute(): void
    {
        /* @var Redis $redis */
        $redis = ApplicationContext::getContainer()->get(RedisFactory::class)->get('business');
        if (!$redis) {
            throw new BusinessException(0, '获取Redis失败!');
        }
        do {
            $ids = $redis->sPop('item_viewed_or_liked', 10);
            if (!$ids) {
                return;
            }
            $models = ContentItem::findManyFromCache($ids);
            foreach ($models as $model) {
                ContentItem::query()
                    ->where('id', '=', $model->id)
                    ->update([
                        'viewed_count' => $model->viewed_count,
                        'liked_count' => $model->liked_count,
                    ]);
            }
        } while (true);
    }
}
